package com.work.servlet;

import com.work.bean.Student;
import com.work.bean.Teacher;
import com.work.service.UserService;
import com.work.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Administrator on 2017/9/29.
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doPost(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserService service = new UserServiceImpl();
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();

        if (req.getParameter("username") != null && req.getParameter("password") != null) {

            String username = req.getParameter("username");
            String password = req.getParameter("password");

            int userType = Integer.parseInt(req.getParameter("userType"));

            System.out.println(userType);
            boolean flag = false;
            if (userType == 0) {
                session.setAttribute("type", "学生");
                Student student = service.loginStudent(new Student(username, password));

                if (student != null) {

                    session.setAttribute("studentId", student.getId());
                    session.setAttribute("username", username);
                    session.setAttribute("password", password);
                    resp.sendRedirect("student_index.jsp");
                    flag = true;
                } else {
                    flag = false;
                }

            } else if (userType == 1) {
                session.setAttribute("type", "老师");
                Teacher teacher = service.loginTeacher(new Teacher(username, password));

                if (teacher != null) {
                    session.setAttribute("teacherId", teacher.getId());
                    session.setAttribute("username", username);
                    session.setAttribute("password", password);

                    resp.sendRedirect("teacher_index.jsp");

                    flag = true;
                } else {
                    flag = false;
                }
            }

            session.setAttribute("isLogin", flag);

            if (!flag) {
                session.setAttribute("errorMsg", "用户名或者密码错误");
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }

        }


    }
}
